<template>
  <view class="container">
    <!-- 页面标题 -->
    <view class="header">
      <text class="title">污染预测分析</text>
      <text class="subtitle">AI智能预测三天污染趋势</text>
    </view>

    <!-- 地图容器 -->
    <view class="map-container">
      <view class="map-header">
        <text class="map-title">监测点分布</text>
        <view class="header-right">
          <text class="device-count">设备总数: {{ deviceList?.length || 0 }}</text>
          <button class="location-btn" @click="requestLocation">
            <text class="location-icon">📍</text>
            <text class="location-text">定位</text>
          </button>
        </view>
      </view>
      
       <!-- 日期标签选择器 -->
       <view class="date-selector" v-if="threeDayPrediction.length > 0">
         <view class="selector-header">
           <text class="selector-title">选择预测日期：</text>
           <button class="clear-all-btn" @click="clearAllPredictionData">
             <uni-icons type="trash" size="14" color="#fff"></uni-icons>
             <text>清除所有</text>
           </button>
            </view>
         <view class="date-tags">
           <view 
             class="date-tag" 
             :class="{ 'active': selectedDateIndex === index, 'polluted': day.isPolluted }"
             v-for="(day, index) in threeDayPrediction" 
             :key="index"
             @click="selectDate(index)"
           >
             <text class="date-text">{{ day.date }}</text>
             <text class="status-text" :class="day.status">{{ day.statusText }}</text>
           </view>
         </view>
        </view>
        
      <!-- 腾讯地图组件 -->
      <!-- #ifdef H5 -->
      <view id="pollutionMap" class="map-component"></view>
      <!-- #endif -->

      <!-- #ifdef MP-WEIXIN -->
      <map
        id="pollutionMap"
        class="map-component"
        :longitude="mapConfig?.center?.[0] || 115.489120"
        :latitude="mapConfig?.center?.[1] || 38.814788"
        :scale="mapConfig?.zoom || 10"
        :markers="markers"
        :show-location="true"
        :enable-3D="false"
        :enable-overlooking="false"
        :enable-zoom="true"
        :enable-scroll="true"
        :enable-rotate="false"
        :enable-satellite="false"
        :enable-poi="true"
        :show-compass="false"
        :show-scale="true"
        :min-scale="3"
        :max-scale="20"
        :key="mapConfig?.key"
        @markertap="onMarkerTap"
        @regionchange="onRegionChange"
        @updated="onMapUpdated"
        @tap="onMapTap"
      >
        <cover-view class="map-legend">
          <cover-view class="legend-item">
            <cover-view class="legend-color online"></cover-view>
            <cover-text class="legend-text">在线</cover-text>
          </cover-view>
          <cover-view class="legend-item">
            <cover-view class="legend-color offline"></cover-view>
            <cover-text class="legend-text">离线</cover-text>
          </cover-view>
          <cover-view class="legend-item">
            <cover-view class="legend-color fault"></cover-view>
            <cover-text class="legend-text">故障</cover-text>
          </cover-view>
          <cover-view class="legend-item">
            <cover-view class="legend-color pollution"></cover-view>
            <cover-text class="legend-text">污染区域</cover-text>
          </cover-view>
        </cover-view>
      </map>
      <!-- #endif -->
        </view>
        
    <!-- 监测点列表 -->
    <view class="device-panel">
      <view class="panel-header">
        <text class="panel-title">监测点列表</text>
        <view class="legend">
          <view class="legend-item">
            <view class="legend-dot online"></view>
            <text class="legend-text">在线</text>
            </view>
          <view class="legend-item">
            <view class="legend-dot offline"></view>
            <text class="legend-text">离线</text>
        </view>
          <view class="legend-item">
            <view class="legend-dot fault"></view>
            <text class="legend-text">故障</text>
            </view>
        </view>
        </view>
        
      <scroll-view scroll-y class="device-list">
        <view class="device-item" :class="{ 'fault-device': device.status === 'fault' }" v-for="device in deviceList" :key="device.id" @click="selectDevice(device)">
          <view class="device-info">
            <view class="device-header">
              <text class="device-name" :class="{ 'fault-name': device.status === 'fault' }">{{ device.name }}</text>
              <text class="status-text" :class="{ 'fault-status': device.status === 'fault' }">{{ getStatusText(device.status) }}</text>
              <view class="device-status" :class="device.status"></view>
            </view>
            <text class="device-location" :class="{ 'fault-location': device.status === 'fault' }">{{ device.location }}</text>
            <view class="device-data">
              <text class="data-item" :class="{ 'fault-data-item': isPhFault(device.ph) }">pH: {{ device.ph }}</text>
              <text class="data-item" :class="{ 'fault-data-item': isTempFault(device.temp) }">温度: {{ device.temp }}°C</text>
              <text class="data-item" :class="{ 'fault-data-item': isNtuFault(device.ntu) }">浊度: {{ device.ntu }} NTU</text>
            </view>
            <!-- 污染预测按钮 -->
            <view class="device-actions">
              <button class="predict-btn" @click.stop="startPollutionPrediction(device)" :disabled="isPredicting">
                <text v-if="isPredicting && selectedDevice?.id === device.id">预测中...</text>
                <text v-else>污染预测</text>
        </button>
      </view>
          </view>
          <uni-icons type="right" size="16" :color="device.status === 'fault' ? '#ff4444' : '#ccc'"></uni-icons>
        </view>
      </scroll-view>
    </view>

    <!-- 污染预测结果弹窗 -->
    <view class="prediction-modal" v-if="showPredictionModal" @click="closePredictionModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">污染预测分析结果</text>
          <text class="close-btn" @click="closePredictionModal">×</text>
      </view>
      
        <view class="modal-body">
          <!-- 设备信息 -->
          <view class="device-info-section" v-if="selectedDevice">
            <text class="section-title">监测设备信息</text>
            <view class="info-item">
              <text class="info-label">设备名称：</text>
              <text class="info-value">{{ selectedDevice.name }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">位置：</text>
              <text class="info-value">{{ selectedDevice.location }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">坐标：</text>
              <text class="info-value">{{ selectedDevice.latitude }}, {{ selectedDevice.longitude }}</text>
      </view>
    </view>

          <!-- 污染状态 -->
          <view class="pollution-status-section" v-if="predictionResult?.isPolluted !== undefined">
            <text class="section-title">污染检测状态</text>
            <view class="pollution-status" :class="{ 'polluted': predictionResult.isPolluted, 'normal': !predictionResult.isPolluted }">
              <uni-icons :type="predictionResult.isPolluted ? 'fire' : 'checkmarkempty'" size="20" :color="predictionResult.isPolluted ? '#ff4444' : '#4cd964'"></uni-icons>
              <text>{{ predictionResult.isPolluted ? '检测到污染' : '水质正常' }}</text>
            </view>
      </view>
      
          <!-- 三天预测结果 -->
          <view class="three-day-prediction-section" v-if="predictionResult?.threeDayPrediction">
            <text class="section-title">三天污染预测</text>
            <view class="day-prediction-list">
              <view class="day-prediction-item" v-for="(day, index) in predictionResult.threeDayPrediction" :key="index">
                <view class="day-header">
                  <text class="day-title">{{ day.date }}</text>
                  <text class="day-status" :class="day.status">{{ day.statusText }}</text>
            </view>
                <view class="day-details">
                  <text class="day-concentration">污染浓度: {{ day.concentration }}</text>
                  <text class="day-description">{{ day.description }}</text>
                </view>
              </view>
      </view>
    </view>

          <!-- 附近化工厂分析 -->
          <view class="factory-analysis-section" v-if="predictionResult?.nearbyFactories">
            <text class="section-title">附近化工厂分析</text>
            <view class="factory-list">
              <view class="factory-item" v-for="factory in predictionResult.nearbyFactories" :key="factory.id">
                <view class="factory-header">
                  <text class="factory-name">{{ factory.name }}</text>
                  <text class="factory-distance">{{ factory.distance }}km</text>
                </view>
                <view class="factory-details">
                  <text class="factory-industry">行业：{{ factory.industry }}</text>
                  <text class="factory-pollutants">主要污染物：{{ factory.mainPollutants }}</text>
                  <text class="factory-risk" :class="factory.riskLevel">风险等级：{{ factory.riskLevel }}</text>
                </view>
              </view>
            </view>
      </view>
      
          <!-- 污染预测结果 -->
          <view class="prediction-result-section" v-if="predictionResult?.prediction">
            <text class="section-title">污染预测结果</text>
            <view class="prediction-content">
              <text class="prediction-text">{{ predictionResult.prediction }}</text>
      </view>
    </view>

          <!-- 建议措施 -->
          <view class="recommendations-section" v-if="predictionResult?.recommendations">
            <text class="section-title">建议措施</text>
            <view class="recommendations-list">
              <text class="recommendation-item" v-for="(rec, index) in predictionResult.recommendations" :key="index">
                {{ index + 1 }}. {{ rec }}
              </text>
            </view>
      </view>
      
          <!-- 污染区域控制 -->
          <view class="pollution-area-control-section" v-if="showPollutionAreas && predictionResult?.isPolluted">
            <text class="section-title">污染区域控制</text>
            <view class="control-buttons">
              <button class="control-btn clear-btn" @click="clearPollutionAreas">
                <uni-icons type="trash" size="16" color="#fff"></uni-icons>
                <text>清除污染区域</text>
              </button>
              <button class="control-btn info-btn" @click="showPollutionAreaInfo">
                <uni-icons type="info" size="16" color="#fff"></uni-icons>
                <text>区域信息</text>
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { onShow, onHide } from '@dcloudio/uni-app'
import { getLatestRedisData } from '@/api/waterQuality.js'
import { getMapDeviceList, getDeviceLatestData } from '@/api/device.js'
import { pollutionApi } from '@/api/pollution.js'
import { TENCENT_MAP_CONFIG } from '@/config/tencent-map.js'
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'

// 地图配置
const mapConfig = ref(TENCENT_MAP_CONFIG)

// 腾讯地图 SDK 实例
const qqmapsdk = ref({})

// 用户位置信息
const userLocation = ref({
  latitude: 38.814788,
  longitude: 115.489120,
  address: ''
})

// 监测指标正常范围
const NORMAL_RANGE = {
  ph: { min: 6.5, max: 8.5 },
  temp: { min: 20, max: 30 },
  ntu: { min: 0, max: 3000 }
}

// 真实数据监测点ID
const REAL_DEVICE_ID = "ESP8266_001"

// 监测点001的真实数据对象
const realDeviceData = ref({
  id: "ESP8266_001",
  name: "监测点001",
  location: "河北省保定市莲池区博学路",
  latitude: 38.814788,
  longitude: 115.489120,
  ph: 7.12,
  temp: 28,
  ntu: 0,
  status: "online"
})

// 设备列表
const deviceList = ref([
  realDeviceData.value
])

const stats = ref({
  total: 0,
  online: 0,
  offline: 0,
  fault: 0
})

// 弹窗相关
const showDeviceModal = ref(false)
const selectedDevice = ref(null)

// 污染预测相关状态
const isAnalyzing = ref(false)
const isPredicting = ref(false)
const showPredictionModal = ref(false)
const predictionResult = ref(null)

// 污染区域相关状态
const pollutionAreas = ref([])
const showPollutionAreas = ref(false)

// 三天预测数据和日期选择
const threeDayPrediction = ref([])
const selectedDateIndex = ref(0)

// 逆地理编码防抖
const reverseGeocodeCache = new Map()
const reverseGeocodeTimers = new Map()

// 地图标记点
const markers = computed(() => {
  return deviceList.value.map((device, index) => ({
    id: device.id,
    latitude: device.latitude,
    longitude: device.longitude,
    title: device.name,
    width: 20,
    height: 20,
    iconPath: getMarkerIcon(device.id),
    callout: {
      content: `${device.name}\n${device.location}\n状态: ${getStatusText(device.status)}\n pH: ${device.ph}  温度: ${device.temp}°C  浊度: ${device.ntu}NTU`,
      color: '#333',
      fontSize: 12,
      borderRadius: 4,
      bgColor: '#fff',
      padding: 8,
      display: 'BYCLICK'
    }
  }))
})

onMounted(() => {
  console.log('污染预测页面加载完成')
  
  if (!mapConfig.value || !mapConfig.value.key) {
    console.error('错误：腾讯地图Key未配置')
    uni.showModal({
      title: '配置错误',
      content: '腾讯地图Key未配置，地图功能无法使用',
      showCancel: false
    })
    return
  }
  
  initTencentMap()
  loadDeviceData()
})

onUnmounted(() => {
  stopSimulateTimer()
  stopRealDataTimer()
  clearPollutionAreas()
})

onShow(() => {
  console.log('污染预测页面显示')
  fetchRealDeviceLatest()
  startSimulateTimer()
  startRealDataTimer()
})

onHide(() => {
  console.log('污染预测页面隐藏')
  stopSimulateTimer()
  stopRealDataTimer()
  clearPollutionAreas()
})

// 判断单个数据项是否异常
const isPhFault = (ph) => {
  return ph < NORMAL_RANGE.ph.min || ph > NORMAL_RANGE.ph.max
}

const isTempFault = (temp) => {
  return temp < NORMAL_RANGE.temp.min || temp > NORMAL_RANGE.temp.max
}

const isNtuFault = (ntu) => {
  return ntu < NORMAL_RANGE.ntu.min || ntu > NORMAL_RANGE.ntu.max
}

const updateStats = () => {
  const total = deviceList.value.length
  let online = 0, fault = 0, offline = 0
  deviceList.value.forEach(d => {
    if (d.status === 'online') online++
    else if (d.status === 'fault') fault++
    else offline++
  })
  stats.value = { total, online, offline, fault }
}

const simulateOnce = () => {
  deviceList.value = deviceList.value.map(d => {
    if (d.id === REAL_DEVICE_ID) {
      return d
    }
    return d
  })
  updateStats()
}

let simulateTimer = null
function startSimulateTimer() {
  if (simulateTimer) return
  simulateOnce()
  simulateTimer = setInterval(simulateOnce, 30 * 1000)
}

function stopSimulateTimer() {
  if (simulateTimer) {
    clearInterval(simulateTimer)
    simulateTimer = null
  }
}

// 初始化腾讯地图
function initTencentMap() {
  // #ifdef MP-WEIXIN
  try {
    const QQMapWX = require('../../common/lib/qqmap-wx-jssdk.min.js')
    const mapKey = mapConfig.value.key
    if (!mapKey) {
      console.error('腾讯地图 Key 未配置')
      uni.showToast({ title: '地图Key未配置', icon: 'none' })
      return
    }
    qqmapsdk.value = new QQMapWX({ key: mapKey })
    console.log('小程序 - 腾讯地图 SDK 初始化成功')
    
    initMap()
    getUserLocation()
  } catch (error) {
    console.error('小程序 - 地图 SDK 加载失败:', error)
    uni.showToast({ title: '地图加载失败', icon: 'none' })
  }
  // #endif

  // #ifdef H5
  console.log('H5 环境 - 加载腾讯地图 SDK 脚本')
  
  const oldScript = document.querySelector('script[src*="map.qq.com/api/js"]')
  if (oldScript) oldScript.remove()
  if (window.initPollutionMapH5) delete window.initPollutionMapH5

  const script = document.createElement('script')
  script.src = `https://map.qq.com/api/js?v=2.exp&key=${mapConfig.value.key}&callback=initPollutionMapH5&libraries=geometry`
  script.onerror = () => {
    console.error('H5 - 地图 SDK 加载失败')
    uni.showToast({ title: 'H5地图加载失败', icon: 'none' })
  }
  
  window.initPollutionMapH5 = () => {
    if (window.pollutionMapInstance) {
      console.log('H5 - 地图已初始化，跳过重复创建')
      getUserLocation()
      return
    }
    console.log('H5 - 腾讯地图 SDK 加载成功')
    initMapForH5()
    getUserLocation()
  }
  
  document.body.appendChild(script)
  // #endif
}

// 新增 H5 地图初始化方法
function initMapForH5() {
  // #ifdef H5
  if (!window.qq || !window.qq.maps) {
    console.error('H5 - 地图 SDK 未加载完成')
    return
  }

  let retryCount = 0
  const getMapContainer = () => {
    const mapContainer = document.getElementById('pollutionMap')
    if (mapContainer) {
      initMapInstance(mapContainer)
    } else if (retryCount < 3) {
      retryCount++
      setTimeout(getMapContainer, 500)
      console.log(`H5 - 重试获取地图容器（${retryCount}/3）`)
        } else {
      console.error('H5 - 多次重试仍未找到地图容器')
    }
  }

  const initMapInstance = (mapContainer) => {
    try {
      const center = new window.qq.maps.LatLng(
        mapConfig.value.center[1],
        mapConfig.value.center[0]
      )
      window.pollutionMapInstance = new window.qq.maps.Map(mapContainer, {
        center: center,
        zoom: mapConfig.value.zoom || 10,
        disableDefaultUI: false,
        zoomControl: true,
        scrollwheel: true,
        disableDoubleClickZoom: false,
        gestureHandling: 'auto'
      })
      console.log('H5 - 地图初始化成功')
      
      // 初始化信息窗
      if (!window.pollutionInfoWindow) {
        window.pollutionInfoWindow = new window.qq.maps.InfoWindow({ map: window.pollutionMapInstance })
      }

      // 初始化标记点容器
      if (!window.pollutionMarkersById) window.pollutionMarkersById = {}
      if (!window.pollutionCirclesById) window.pollutionCirclesById = {}

      // 添加标记点和圆形围栏
      deviceList.value.forEach(device => {
        const position = new window.qq.maps.LatLng(device.latitude, device.longitude)
        
        // 添加标记点
        const marker = new window.qq.maps.Marker({
          position,
          map: window.pollutionMapInstance,
          title: device.name
        })

        // 设置状态颜色图标
        const color = getStatusColor(device.status)
        const iconUrl = buildStatusSvgDataUrl(color, device.status)
        const size = new window.qq.maps.Size(24, 24)
        const markerImage = new window.qq.maps.MarkerImage(iconUrl, null, null, null, size)
        marker.setIcon(markerImage)

         // 添加圆形围栏（电子栅栏）
         const fillColor = new window.qq.maps.Color(33, 150, 243, 0.2)
         const strokeColor = new window.qq.maps.Color(33, 150, 243, 0.6)
         
         const circle = new window.qq.maps.Circle({
           center: position,
           radius: 2000, // 2公里半径
           map: window.pollutionMapInstance,
           fillColor: fillColor,
           strokeColor: strokeColor,
           strokeWeight: 2
         })

        // 绑定点击展示信息窗
        window.qq.maps.event.addListener(marker, 'click', () => {
          const isFault = device.status === 'fault'
          const faultStyle = isFault ? 'color: #ff4444; font-weight: bold;' : ''
          const faultBgStyle = isFault ? 'background-color: #fff5f5; border: 2px solid #ff4444; border-radius: 8px; padding: 8px;' : ''
          
          const phFault = isPhFault(device.ph)
          const tempFault = isTempFault(device.temp)
          const ntuFault = isNtuFault(device.ntu)
          
          const phStyle = phFault ? 'color: #ff4444; font-weight: bold; background-color: #fff0f0; padding: 2px 4px; border-radius: 4px;' : ''
          const tempStyle = tempFault ? 'color: #ff4444; font-weight: bold; background-color: #fff0f0; padding: 2px 4px; border-radius: 4px;' : ''
          const ntuStyle = ntuFault ? 'color: #ff4444; font-weight: bold; background-color: #fff0f0; padding: 2px 4px; border-radius: 4px;' : ''
          
          const html = `<div style="min-width:180px;line-height:1.6; ${faultBgStyle}">
              <div style="font-weight:600;margin-bottom:4px; ${faultStyle}">${device.name}</div>
              <div style="${faultStyle}">${device.location}</div>
              <div style="${faultStyle}">状态：${getStatusText(device.status)}</div>
              <div style="${faultStyle}">pH：<span style="${phStyle}">${device.ph}</span>，温度：<span style="${tempStyle}">${device.temp}°C</span></div>
              <div style="${faultStyle}">浊度：<span style="${ntuStyle}">${device.ntu} NTU</span></div>
              <div style="font-size:12px;color:#666;margin-top:4px;">监测范围：2公里</div>
          </div>`
          window.pollutionInfoWindow.setContent(html)
          window.pollutionInfoWindow.setPosition(position)
          window.pollutionInfoWindow.open()
        })

        window.pollutionMarkersById[device.id] = marker
        window.pollutionCirclesById[device.id] = circle
      })

      // 初始化污染区域数组
      if (!window.pollutionPollutionAreas) {
        window.pollutionPollutionAreas = []
        }
      } catch (error) {
      console.error('H5 - 地图初始化失败:', error)
    }
  }

  getMapContainer()
  // #endif
}

// 修改原 initMap 方法，适配小程序地图初始化
const initMap = () => {
  console.log('小程序 - 初始化地图组件')
}

// 获取状态颜色
const getStatusColor = (status) => {
  if (status === 'online') return '#4cd964'
  if (status === 'fault') return '#dd524d'
  return '#999999'
}

// 构建状态SVG图标
const buildStatusSvgDataUrl = (color, status = 'online') => {
  let svg
  if (status === 'fault') {
    svg = `<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'>
      <circle cx='12' cy='12' r='10' fill='${color}' stroke='#ff0000' stroke-width='2' />
      <circle cx='12' cy='12' r='6' fill='white' opacity='0.9' />
      <text x='12' y='16' text-anchor='middle' font-family='Arial' font-size='12' font-weight='bold' fill='#ff0000'>!</text>
    </svg>`
  } else {
    svg = `<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'>
      <circle cx='12' cy='12' r='10' fill='${color}' />
      <circle cx='12' cy='12' r='4' fill='white' opacity='0.2' />
    </svg>`
  }
  return 'data:image/svg+xml;utf8,' + encodeURIComponent(svg)
}

// 获取标记点图标
const getMarkerIcon = (deviceId) => {
  const device = deviceList.value.find(d => d.id === deviceId)
  if (device) {
    switch(device.status) {
      case 'online':
        return '/static/images/marker-online.png'
      case 'offline':
        return '/static/images/marker-offline.png'
      case 'fault':
        return '/static/images/marker-fault.png'
    }
  }
  return 'https://mapapi.qq.com/webapi/staticimage/v2?size=20x20&color=FF0000&format=png'
}

// 定位到固定坐标
function getUserLocation(options = {}) {
  console.log('定位到固定坐标')
  
        uni.showToast({
    title: '定位成功',
    icon: 'success',
    duration: 2000
  })
  
  userLocation.value = {
    latitude: 38.814788,
    longitude: 115.489120,
    address: '固定位置 (115.489120, 38.814788)'
  }
  
  updateMapCenter(
    userLocation.value.longitude,
    userLocation.value.latitude
  )
  
  console.log('定位到固定坐标完成:', userLocation.value)
  
  options.onComplete?.()
}

// 更新地图中心
const updateMapCenter = (longitude, latitude) => {
  // #ifdef H5
  if (window.qq && window.qq.maps && window.pollutionMapInstance) {
    try {
      const lat = parseFloat(latitude)
      const lng = parseFloat(longitude)
      
      if (isNaN(lat) || isNaN(lng)) {
        console.error('H5 - 无效的坐标值:', { latitude, longitude })
        return
      }
      
      if (lat < -90 || lat > 90 || lng < -180 || lng > 180) {
        console.error('H5 - 坐标超出有效范围:', { lat, lng })
        return
      }
      
      console.log('H5 - 准备更新地图中心:', { lat, lng })
      
      const newCenter = new window.qq.maps.LatLng(lat, lng)
      console.log('H5 - LatLng对象创建成功:', newCenter)
      
      window.pollutionMapInstance.setCenter(newCenter)
      console.log('H5 - 地图中心点已更新到用户位置')
      
    } catch (error) {
      console.error('H5 - 更新地图中心失败:', error)
    }
  } else {
    console.error('H5 - 地图实例未初始化或腾讯地图SDK未加载')
  }
  // #endif
  
  // #ifdef MP-WEIXIN
  console.log('小程序 - 准备更新地图中心:', { longitude, latitude })
  
  const lat = parseFloat(latitude)
  const lng = parseFloat(longitude)
  
  if (isNaN(lat) || isNaN(lng)) {
    console.error('小程序 - 无效的坐标值:', { latitude, longitude })
    return
  }
  
  if (lat < -90 || lat > 90 || lng < -180 || lng > 180) {
    console.error('小程序 - 坐标超出有效范围:', { lat, lng })
    return
  }
  
  mapConfig.value.center = [lng, lat]
  console.log('小程序 - 地图中心点已更新:', mapConfig.value.center)
  // #endif
}

// 加载设备数据
async function loadDeviceData() {
  console.log('加载设备数据...')
  try {
    const res = await getMapDeviceList()
    if (res && res.code === 200 && res.obj) {
      const backendDevices = res.obj
      console.log('从后端获取到设备数据:', backendDevices)
      
      const convertedDevices = backendDevices.map(device => ({
        id: device.id,
        name: device.name,
        location: device.location || '待获取地址',
        latitude: parseFloat(device.latitude) || 38.814788,
        longitude: parseFloat(device.longitude) || 115.489120,
        status: device.status || 'online',
        ph: 7.0,
        temp: 25.0,
        ntu: 1000,
        deviceCode: device.deviceCode,
        deviceType: device.deviceType,
        manufacturer: device.manufacturer
      }))
      
      const newDeviceList = [realDeviceData.value]
      
      convertedDevices.forEach(device => {
        if (device.id !== REAL_DEVICE_ID) {
          newDeviceList.push(device)
        }
      })
      
      deviceList.value = newDeviceList
      updateStats()
      
      for (let device of deviceList.value) {
        try {
          const dataRes = await getDeviceLatestData(device.id)
          if (dataRes && dataRes.code === 200 && dataRes.obj) {
            const data = dataRes.obj
            device.ph = data.ph || device.ph
            device.temp = data.temp || device.temp
            device.ntu = data.ntu || device.ntu
            device.status = data.status || device.status
          }
        } catch (e) {
          console.warn(`获取设备${device.id}水质数据失败:`, e)
        }
      }
      
      updateStats()
    } else {
      console.warn('获取设备列表失败，使用默认数据')
    }
  } catch (e) {
    console.error('加载设备数据失败:', e)
  }
  
  fetchRealDeviceLatest()
}

// 拉取监测点001的最新数据
async function fetchRealDeviceLatest() {
  try {
    const deviceId = REAL_DEVICE_ID
    const res = await getLatestRedisData(deviceId)
    if (res && res.code === 200 && res.obj) {
      const d = res.obj
      if (typeof d.ph === 'number') realDeviceData.value.ph = +d.ph
      if (typeof d.temp === 'number') realDeviceData.value.temp = +d.temp
      if (typeof d.ntu === 'number') realDeviceData.value.ntu = Math.round(d.ntu)
      if (d.status) realDeviceData.value.status = d.status
      else realDeviceData.value.status = computeStatusFromMetrics(realDeviceData.value.ph, realDeviceData.value.temp, realDeviceData.value.ntu)
      if (d.latitude && d.longitude) {
        realDeviceData.value.latitude = d.latitude
        realDeviceData.value.longitude = d.longitude
      }
      if (d.location) realDeviceData.value.location = d.location
      
      deviceList.value[0] = { ...realDeviceData.value }
      updateStats()
    }
  } catch (e) {
    console.error('获取真实数据失败:', e)
  }
}

const computeStatusFromMetrics = (ph, temp, ntu) => {
  const phOk = ph >= NORMAL_RANGE.ph.min && ph <= NORMAL_RANGE.ph.max
  const tempOk = temp >= NORMAL_RANGE.temp.min && temp <= NORMAL_RANGE.temp.max
  const ntuOk = ntu >= NORMAL_RANGE.ntu.min && ntu <= NORMAL_RANGE.ntu.max
  return phOk && tempOk && ntuOk ? 'online' : 'fault'
}

// 定时更新真实数据
let realDataTimer = null
function startRealDataTimer() {
  if (realDataTimer) clearInterval(realDataTimer)
  realDataTimer = setInterval(() => {
    fetchRealDeviceLatest()
  }, 10000)
}

function stopRealDataTimer() {
  if (realDataTimer) {
    clearInterval(realDataTimer)
    realDataTimer = null
  }
}

// 手动请求定位
const requestLocation = () => {
  console.log('用户手动请求定位')
  uni.showLoading({ title: '正在定位...' })

  const closeLoading = () => {
    if (uni.getStorageSync('locationLoading')) {
        uni.hideLoading()
      uni.removeStorageSync('locationLoading')
    }
  }
  uni.setStorageSync('locationLoading', true)

  const loadingTimer = setTimeout(closeLoading, 12000)

  getUserLocation({
    onComplete: () => {
      clearTimeout(loadingTimer)
      closeLoading()
    }
  })
}

// 选择设备
const selectDevice = (device) => {
  console.log('选择设备:', device.name)
  
  updateMapCenter(device.longitude, device.latitude)
  
  showDeviceModal.value = true
  selectedDevice.value = device
  
        uni.showToast({
    title: `已定位到${device.name}`,
    icon: 'success',
    duration: 2000
  })
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    online: '在线',
    offline: '离线',
    fault: '故障'
  }
  return statusMap[status] || '未知'
}

// 关闭设备信息弹窗
const closeDeviceModal = () => {
  showDeviceModal.value = false
  selectedDevice.value = null
}

// 开始污染预测
const startPollutionPrediction = async (device) => {
  if (isPredicting.value) return

  try {
    isPredicting.value = true
    selectedDevice.value = device

    uni.showLoading({ title: 'AI污染预测中...' })

    // 构建请求数据
    const requestData = {
      latitude: device.latitude,
      longitude: device.longitude,
      deviceId: device.id,
      deviceName: device.name,
      currentData: {
        ph: device.ph,
        temp: device.temp,
        ntu: device.ntu,
        status: device.status
      },
      timestamp: new Date().toISOString()
    }

    console.log('开始污染预测:', requestData)

    // 调用后端API
    const res = await pollutionApi.analyzeByLocation(requestData)
    console.log('API响应:', res)
        
        if (res.code === 200) {
      // 处理分析结果
      predictionResult.value = {
        nearbyFactories: res.obj?.nearbyFactories || [],
        isPolluted: res.obj?.isPolluted || false,
        pollutionSourceAnalysis: res.obj?.pollutionSourceAnalysis || {},
        prediction: res.obj?.prediction || '分析完成',
        recommendations: res.obj?.recommendations || []
      }

      // 生成三天预测数据
      threeDayPrediction.value = generateThreeDayPrediction(res.obj)
      selectedDateIndex.value = 0 // 默认选择第一天

      // 根据第一天的情况显示污染区域
      const firstDay = threeDayPrediction.value[0]
      if (firstDay.isPolluted) {
        console.log('第一天检测到污染，显示污染区域')
        showPollutionArea(device.latitude, device.longitude, 2000)
      } else {
        console.log('第一天未检测到污染，不显示污染区域')
        clearPollutionAreas()
      }

      showPredictionModal.value = true
          
          uni.showToast({
        title: '污染预测完成',
            icon: 'success'
          })
        } else {
      console.error('API响应失败:', res)
          uni.showToast({
        title: res.msg || '预测失败',
            icon: 'error'
          })
        }
      } catch (error) {
    console.error('污染预测失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'error'
        })
      } finally {
    isPredicting.value = false
        uni.hideLoading()
      }
}

// 生成三天预测数据
const generateThreeDayPrediction = (apiResult) => {
  const today = new Date()
  const predictionData = []
  
  for (let i = 0; i < 3; i++) {
    const date = new Date(today)
    date.setDate(today.getDate() + i)
    
    const dayStr = i === 0 ? '今天' : i === 1 ? '明天' : '后天'
    const dateStr = `${date.getMonth() + 1}.${date.getDate()}`
    
    let status, statusText, concentration, description, isPolluted, pollutionReason
    
    if (apiResult?.isPolluted) {
      if (i === 0) {
        // 今天有污染
        status = 'polluted'
        statusText = '有污染'
        concentration = '150-200 μg/m³'
        description = '检测到轻度污染，建议减少户外活动'
        isPolluted = true
        pollutionReason = apiResult.pollutionSourceAnalysis?.primarySuspect?.name || '附近化工厂'
      } else if (i === 1) {
        // 明天污染减轻
        status = 'warning'
        statusText = '轻度污染'
        concentration = '80-120 μg/m³'
        description = '污染浓度下降，但仍需注意防护'
        isPolluted = true
        pollutionReason = '污染源持续影响'
      } else {
        // 后天恢复正常
        status = 'normal'
        statusText = '正常'
        concentration = '30-50 μg/m³'
        description = '污染已消散，空气质量良好'
        isPolluted = false
        pollutionReason = ''
      }
    } else {
      // 没有污染的情况 - 模拟不同的污染情况
      if (i === 0) {
        // 今天正常
        status = 'normal'
        statusText = '正常'
        concentration = '20-40 μg/m³'
        description = '空气质量良好，适合户外活动'
        isPolluted = false
        pollutionReason = ''
      } else if (i === 1) {
        // 明天可能有轻微污染
        status = 'warning'
        statusText = '轻度污染'
        concentration = '60-80 μg/m³'
        description = '预计有轻微污染，注意防护'
        isPolluted = true
        pollutionReason = '气象条件变化'
      } else {
        // 后天恢复正常
        status = 'normal'
        statusText = '正常'
        concentration = '25-35 μg/m³'
        description = '空气质量恢复正常'
        isPolluted = false
        pollutionReason = ''
      }
    }
    
    predictionData.push({
      date: `${dateStr} (${dayStr})`,
      status,
      statusText,
      concentration,
      description,
      isPolluted,
      pollutionReason
    })
  }
  
  return predictionData
}

// 显示污染区域
const showPollutionArea = (latitude, longitude, radius = 2000) => {
  console.log('显示污染区域:', { latitude, longitude, radius })

  const pollutionArea = {
    id: 'pollution_area_' + Date.now(),
    latitude: latitude,
    longitude: longitude,
    radius: radius,
    type: 'pollution',
    strokeColor: '#ff4444',
    fillColor: '#ff4444',
    strokeWidth: 3,
    opacity: 0.3
  }

  pollutionAreas.value.push(pollutionArea)
  showPollutionAreas.value = true

  // 在H5地图上添加污染区域覆盖物
  // #ifdef H5
  if (window.pollutionMapInstance && window.qq?.maps) {
    const center = new window.qq.maps.LatLng(latitude, longitude)

    const circle = new window.qq.maps.Circle({
      center: center,
      radius: radius,
      map: window.pollutionMapInstance,
      strokeColor: new window.qq.maps.Color(255, 68, 68, 0.8),
      fillColor: new window.qq.maps.Color(255, 68, 68, 0.3),
      strokeWeight: 3
    })

    if (!window.pollutionPollutionAreas) {
      window.pollutionPollutionAreas = []
    }
    window.pollutionPollutionAreas.push(circle)

    console.log('H5地图污染区域显示完成')
  }
  // #endif

  // #ifdef MP-WEIXIN
  console.log('小程序地图污染区域状态已更新')
  // #endif
}

// 清除污染区域
const clearPollutionAreas = () => {
  console.log('清除污染区域')

  // #ifdef H5
  if (window.pollutionPollutionAreas) {
    window.pollutionPollutionAreas.forEach(circle => {
      circle.setMap(null)
    })
    window.pollutionPollutionAreas = []
  }
  // #endif

  pollutionAreas.value = []
  showPollutionAreas.value = false

  uni.showToast({
    title: '污染区域已清除',
    icon: 'success'
  })
}

// 显示污染区域信息
const showPollutionAreaInfo = () => {
  if (pollutionAreas.value.length === 0) {
    uni.showToast({
      title: '暂无污染区域',
      icon: 'none'
    })
    return
  }

  const areaInfo = pollutionAreas.value.map(area => 
    `半径: ${area.radius / 1000}km\n坐标: ${area.latitude}, ${area.longitude}`
  ).join('\n\n')

  uni.showModal({
    title: '污染区域信息',
    content: `共 ${pollutionAreas.value.length} 个污染区域:\n\n${areaInfo}`,
    showCancel: false,
    confirmText: '确定'
  })
}

// 选择日期标签
const selectDate = (index) => {
  if (!selectedDevice.value || !threeDayPrediction.value[index]) return
  
  selectedDateIndex.value = index
  const selectedDay = threeDayPrediction.value[index]
  
  console.log(`选择日期: ${selectedDay.date}, 污染状态: ${selectedDay.isPolluted}`)
  
  // 根据选择的日期更新地图污染区域
  if (selectedDay.isPolluted) {
    console.log(`${selectedDay.date} 有污染，显示污染区域`)
    showPollutionArea(selectedDevice.value.latitude, selectedDevice.value.longitude, 2000)
    
    // 显示污染原因
    if (selectedDay.pollutionReason) {
      uni.showToast({
        title: `污染原因: ${selectedDay.pollutionReason}`,
        icon: 'none',
        duration: 3000
      })
    }
  } else {
    console.log(`${selectedDay.date} 无污染，清除污染区域`)
    clearPollutionAreas()
    
    uni.showToast({
      title: `${selectedDay.date} 空气质量良好`,
      icon: 'success',
      duration: 2000
    })
  }
}

// 关闭污染预测弹窗
const closePredictionModal = () => {
  showPredictionModal.value = false
  // 保留污染区域和预测数据，只关闭弹窗
  console.log('关闭预测弹窗，保留污染区域和预测数据')
}

// 清除所有预测数据
const clearAllPredictionData = () => {
  showPredictionModal.value = false
  selectedDevice.value = null
  predictionResult.value = null
  threeDayPrediction.value = []
  selectedDateIndex.value = 0
  clearPollutionAreas()
  console.log('清除所有预测数据')
}

// 标记点击事件
const onMarkerTap = (e) => {
  const markerId = e.detail.markerId
  const device = deviceList.value.find(d => d.id === markerId)
  if (device) {
    selectDevice(device)
  }
}

// 地图区域变化事件
const onRegionChange = (e) => {
  console.log('地图区域变化:', e.detail)
}

// 地图更新事件
const onMapUpdated = (e) => {
  console.log('地图更新:', e)
  if (e.detail && e.detail.scale) {
    mapConfig.value.zoom = e.detail.scale
    console.log('地图缩放级别更新为:', e.detail.scale)
  }
}

// 地图点击事件
const onMapTap = (e) => {
  console.log('地图点击:', e.detail)
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
}

.header {
  text-align: center;
  padding: 40rpx 20rpx;
}

.title {
  font-size: 48rpx;
  font-weight: bold;
  color: #fff;
  display: block;
  margin-bottom: 10rpx;
}

.subtitle {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
  display: block;
}

.map-container {
  background-color: #ffffff;
  border-radius: 10rpx;
  padding: 30rpx;
  margin: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.location-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 20rpx;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 20rpx;
  font-size: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(76, 175, 80, 0.3);
  transition: all 0.3s ease;
}

.location-btn:active {
  transform: scale(0.95);
  background-color: #45a049;
}

.location-icon {
  font-size: 28rpx;
}

.location-text {
  font-size: 24rpx;
  font-weight: 500;
}

.map-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.device-count {
  font-size: 22rpx;
  color: #666;
}

/* 日期选择器样式 */
.date-selector {
  margin-bottom: 20rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  border: 2rpx solid #e9ecef;
}

.selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.selector-title {
  font-size: 24rpx;
  color: #333;
  font-weight: bold;
}

.clear-all-btn {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 8rpx 16rpx;
  background-color: #ff4444;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 20rpx;
  transition: all 0.3s ease;
}

.clear-all-btn:active {
  background-color: #cc3333;
  transform: scale(0.95);
}

.date-tags {
  display: flex;
  gap: 15rpx;
  flex-wrap: wrap;
}

.date-tag {
  flex: 1;
  min-width: 120rpx;
  padding: 15rpx 20rpx;
  border-radius: 12rpx;
  border: 2rpx solid #e9ecef;
  background-color: #fff;
  text-align: center;
  transition: all 0.3s ease;
  cursor: pointer;
}

.date-tag.active {
  border-color: #007aff;
  background-color: #e3f2fd;
  box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.2);
}

.date-tag.polluted {
  border-color: #ff4444;
  background-color: #fff5f5;
}

.date-tag.polluted.active {
  border-color: #ff4444;
  background-color: #ffebee;
  box-shadow: 0 4rpx 12rpx rgba(255, 68, 68, 0.2);
}

.date-text {
  font-size: 22rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 5rpx;
}

.status-text {
  font-size: 18rpx;
  font-weight: 500;
  display: block;
}

.status-text.polluted {
  color: #d32f2f;
}

.status-text.warning {
  color: #f57c00;
}

.status-text.normal {
  color: #2e7d32;
}

.map-component {
  flex: 1;
  width: 100%;
  height: 100%;
  min-height: 200px;
  border-radius: 15rpx;
  overflow: hidden;
  position: relative;
  z-index: 1;
}

.map-legend {
  position: absolute;
  bottom: 20rpx;
  left: 20rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 10rpx;
  padding: 15rpx 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 20rpx;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.legend-color {
  width: 24rpx;
  height: 24rpx;
  border-radius: 50%;
  
  &.online { background-color: #4CAF50; }
  &.offline { background-color: #9E9E9E; }
  &.fault { background-color: #F44336; }
  &.pollution { background-color: #ff4444; }
}

.legend-text {
  font-size: 24rpx;
  color: #333;
}

.device-panel {
  height: 400rpx;
  background-color: #ffffff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.panel-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.legend {
  display: flex;
  gap: 20rpx;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.legend-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  
  &.online { background-color: #4cd964; }
  &.offline { background-color: #999999; }
  &.fault { background-color: #dd524d; }
}

.legend-text {
  font-size: 20rpx;
  color: #666;
}

.device-list {
  height: 300rpx;
}

.device-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.device-info {
  flex: 1;
}

.device-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.status-text {
  font-size: 22rpx;
  color: #666;
}

.device-name {
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
}

.device-status {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  
  &.online { background-color: #4cd964; }
  &.offline { background-color: #999999; }
  &.fault { 
    background-color: #dd524d;
    animation: fault-blink 1.5s infinite;
  }
}

.fault-device {
  background-color: #fff5f5;
  border-left: 4rpx solid #ff4444;
  box-shadow: 0 2rpx 8rpx rgba(255, 68, 68, 0.1);
}

.fault-name {
  color: #ff4444 !important;
  font-weight: bold;
}

.fault-status {
  color: #ff4444 !important;
  font-weight: bold;
}

.fault-location {
  color: #ff6666 !important;
}

.fault-data-item {
  color: #ff4444 !important;
  font-weight: bold;
}

@keyframes fault-blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0.3; }
}

.device-location {
  font-size: 22rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.device-data {
  display: flex;
  gap: 20rpx;
}

.data-item {
  font-size: 20rpx;
  color: #999;
}

.device-actions {
  margin-top: 8rpx;
}

.predict-btn {
  padding: 8rpx 16rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 18rpx;
  font-weight: bold;
  transition: all 0.3s ease;
}

.predict-btn:active {
  transform: scale(0.95);
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

.predict-btn:disabled {
  background: #ccc;
  color: #999;
  transform: none;
}

/* 污染预测结果弹窗样式 */
.prediction-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 10000;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
}

.modal-content {
  background-color: #fff;
  border-radius: 20rpx;
  width: 100%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 10rpx 40rpx rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #fff;
}

.close-btn {
  font-size: 40rpx;
  color: rgba(255, 255, 255, 0.8);
  cursor: pointer;
}

.modal-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.device-info-section,
.pollution-status-section,
.three-day-prediction-section,
.factory-analysis-section,
.prediction-result-section,
.recommendations-section,
.pollution-area-control-section {
  margin-bottom: 30rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  padding-bottom: 10rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.info-item {
  display: flex;
  margin-bottom: 15rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.info-label {
  font-size: 24rpx;
  color: #666;
  width: 120rpx;
  flex-shrink: 0;
}

.info-value {
  font-size: 24rpx;
  color: #333;
  flex: 1;
}

.pollution-status {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 16rpx;
  border-radius: 12rpx;
  font-weight: 600;
  font-size: 28rpx;
}

.pollution-status.polluted {
  background: #ffe6e6;
  color: #d32f2f;
  border: 2rpx solid #ffcdd2;
}

.pollution-status.normal {
  background: #e8f5e8;
  color: #2e7d32;
  border: 2rpx solid #c8e6c9;
}

/* 三天预测样式 */
.day-prediction-list {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.day-prediction-item {
  background-color: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  border-left: 4rpx solid #4CAF50;
}

.day-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.day-title {
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
}

.day-status {
  font-size: 20rpx;
  font-weight: bold;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  
  &.polluted {
    background-color: #ffebee;
    color: #d32f2f;
  }
  
  &.warning {
    background-color: #fff3e0;
    color: #f57c00;
  }
  
  &.normal {
    background-color: #e8f5e8;
    color: #2e7d32;
  }
}

.day-details {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.day-concentration {
  font-size: 20rpx;
  color: #666;
}

.day-description {
  font-size: 20rpx;
  color: #666;
}

.factory-list {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.factory-item {
  background-color: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  border-left: 4rpx solid #4CAF50;
}

.factory-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.factory-name {
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
}

.factory-distance {
  font-size: 20rpx;
  color: #666;
  background-color: #e9ecef;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
}

.factory-details {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.factory-industry,
.factory-pollutants {
  font-size: 20rpx;
  color: #666;
}

.factory-risk {
  font-size: 20rpx;
  font-weight: bold;

  &.high { color: #ff4444; }
  &.medium { color: #ffa500; }
  &.low { color: #4cd964; }
}

.prediction-content {
  background-color: #f8f9fa;
  padding: 20rpx;
  border-radius: 12rpx;
  border: 1rpx solid #e9ecef;
}

.prediction-text {
  font-size: 24rpx;
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
  word-break: break-word;
}

.recommendations-list {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.recommendation-item {
  font-size: 22rpx;
  line-height: 1.5;
  color: #333;
  padding: 10rpx 15rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border-left: 3rpx solid #4CAF50;
}

/* 污染区域控制样式 */
.pollution-area-control-section {
  margin-top: 30rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
}

.control-buttons {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
}

.control-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  padding: 20rpx;
  border-radius: 12rpx;
  border: none;
  font-size: 28rpx;
  color: #fff;
}

.clear-btn {
  background-color: #ff4444;
}

.clear-btn:active {
  background-color: #cc3333;
}

.info-btn {
  background-color: #007aff;
}

.info-btn:active {
  background-color: #0056b3;
}
</style>